﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Eagles.Application.Model.Login.Requset;
using Eagles.Application.Model.Operator.Requset;
using Eagles.Application.Model.PartyMember.Requset;
using Eagles.Base.Cache;
using Eagles.Base.DataBase;
using Eagles.DomainService.Model.Oper;
using Eagles.DomainService.Model.User;
using Eagles.Interface.DataAccess;

namespace Eagles.DomianService.DataAccess
{
    public class OperDataAccess : IOperDataAccess
    {
        private readonly IDbManager dbManager;
        private readonly ICacheHelper cacheHelper;

        public OperDataAccess(IDbManager dbManager, ICacheHelper cacheHelper)
        {
            this.dbManager = dbManager;
            this.cacheHelper = cacheHelper;
        }
        public int EditOper(TbOper mod)
        {
            return dbManager.Excuted(@" UPDATE `eagles`.`tb_oper`
SET
`OrgId` = @OrgId,
`OperId` = @OperId,
`OperName` = @OperName,
`GroupId` = @GroupId,
`Status` = @Status,
`Password` = @Password,
`BranchId` = @BranchId,
`Nickname` = @Nickname
WHERE 
`OperId` = @OperId
 ", mod);
        }

        public int CreateOper(TbOper mod)
        {
            return dbManager.Excuted(@" INSERT INTO `eagles`.`tb_oper`
(`OrgId`,
`OperId`,
`OperName`,
`CreateTime`,
`GroupId`,
`Status`,
`Password`,
`BranchId`,
`Nickname`)
VALUES
(@OrgId,
@OperId,
@OperName,
@CreateTime,
@GroupId,
@Status,
@Password,
@BranchId,
@Nickname);
 ", mod);
        }

        public int RemoveOper(RemoveOperatorRequset requset)
        {
            return dbManager.Excuted(@" DELETE FROM `eagles`.`tb_oper` 
              where OperId=@OperId
", new { requset.OperId });
        }

        public TbOper GetOperDetail(int operId)
        {
            var sql = new StringBuilder();
            var dynamicParams = new DynamicParameters();

            sql.Append(@" SELECT `tb_oper`.`OrgId`,
    `tb_oper`.`OperId`,
    `tb_oper`.`OperName`,
    `tb_oper`.`CreateTime`,
    `tb_oper`.`GroupId`,
    `tb_oper`.`Status`,
    `tb_oper`.`Password`,
    `tb_oper`.`BranchId`,
`tb_oper`.`Nickname`
FROM `eagles`.`tb_oper`
  where OperId=@OperId;
 ");
            dynamicParams.Add("OperId", operId);

            return dbManager.QuerySingle<TbOper>(sql.ToString(), dynamicParams);
        }

        public List<TbOper> GetOperList(GetOperatorRequset requset, out int totalCount)
        {

            var sql = new StringBuilder();
            var parameter = new StringBuilder();
            var dynamicParams = new DynamicParameters();

            var token = cacheHelper.GetData<TbUserToken>(requset.Token);

            if (token.OrgId > 0 && !requset.OrgBranch)
            {
                parameter.Append(" and  a.OrgId = @OrgId ");
                dynamicParams.Add("OrgId", token.OrgId);
            }

            if (!string.IsNullOrWhiteSpace(requset.OperName))
            {
                parameter.Append(" and a.OperName like @OperName ");
                dynamicParams.Add("OperName", '%' + requset.OperName + '%');
            }



            if (requset.StartTime != null)
            {
                parameter.Append(" and a.CreateTime >= @StartTime ");
                dynamicParams.Add("StartTime", requset.StartTime);
            }

            if (requset.EndTime != null)
            {
                parameter.Append(" and a.CreateTime <= @EndTime ");
                dynamicParams.Add("EndTime", requset.EndTime);
            }

            if (requset.OrgBranch)
            {
                parameter.Append(" and a.BranchId=0 ");
            }
            else
            {
                parameter.Append(" and a.BranchId>0 ");
            }

            sql.AppendFormat(@"SELECT count(*)
FROM `eagles`.`tb_oper` a  where 1=1  {0} ;
 ", parameter);
            totalCount = dbManager.ExecuteScalar<int>(sql.ToString(), dynamicParams);

            sql.Clear();

            dynamicParams.Add("pageStart", (requset.PageNumber - 1) * requset.PageSize);
            dynamicParams.Add("pageNum", requset.PageNumber);
            dynamicParams.Add("pageSize", requset.PageSize);

            sql.AppendFormat(@" SELECT 
	a.OrgId,
    a.OperId,
    a.OperName,
    a.CreateTime,
    a.GroupId,
    a.Status,
    a.Password,
    a.BranchId,
   a.Nickname,
   b.OrgName
FROM eagles.tb_oper a 
inner join eagles.tb_org_info b on a.OrgId=b.orgId

  where  1=1  {0}   order by a.CreateTime desc limit  @pageStart ,@pageSize;
 ", parameter);

            return dbManager.Query<TbOper>(sql.ToString(), dynamicParams);
        }

        public int GetOperListByAuthorityGroupId(int requsetAuthorityGroupId)
        {

            var sql = new StringBuilder();
            var dynamicParams = new DynamicParameters();

            sql.Append(@" SELECT `tb_oper`.`OrgId`,
    `tb_oper`.`OperId`,
    `tb_oper`.`OperName`,
    `tb_oper`.`CreateTime`,
    `tb_oper`.`GroupId`,
    `tb_oper`.`Status`,
    `tb_oper`.`Password`,
    `tb_oper`.`Nickname`
FROM `eagles`.`tb_oper`
  where GroupId=@GroupId;
 ");
            dynamicParams.Add("GroupId", requsetAuthorityGroupId);

            return dbManager.Query<TbOper>(sql.ToString(), dynamicParams).Count;
        }

        public TbOper GetOperInfo(string account, int orgId)
        {
            return dbManager.QuerySingle<TbOper>(@" SELECT `tb_oper`.`OrgId`,
    `tb_oper`.`OperId`,
    `tb_oper`.`OperName`,
    `tb_oper`.`CreateTime`,
    `tb_oper`.`GroupId`,
    `tb_oper`.`Status`,
    `tb_oper`.`Password`,
    `tb_oper`.`LoginErrorCount`,
    `tb_oper`.`LockingTime`,
     `tb_oper`.`Nickname`,
BranchId
FROM `eagles`.`tb_oper`
WHERE `OperName` = @OperName 
 ", new { OperName = account});

        }

        public List<TbOper> GetOperList(List<int> list)
        {


            var sql = new StringBuilder();
            var dynamicParams = new DynamicParameters();

            sql.Append(@" SELECT `tb_oper`.`OrgId`,
    `tb_oper`.`OperId`,
    `tb_oper`.`OperName`,
    `tb_oper`.`CreateTime`,
    `tb_oper`.`GroupId`,
    `tb_oper`.`Status`,
    `tb_oper`.`Password`,
    `tb_oper`.`LoginErrorCount`,
    `tb_oper`.`LockingTime`,
    `tb_oper`.`BranchId`,
    `tb_oper`.`Nickname`
FROM `eagles`.`tb_oper` 
  where OperId  in  @OperId;  
 ");
            dynamicParams.Add("OperId", list.ToArray());

            return dbManager.Query<TbOper>(sql.ToString(), dynamicParams);

        }

        public int CheckOper(string infoOperName, int tokenOrgId)
        {

            var sql = new StringBuilder();
            var dynamicParams = new DynamicParameters();

            sql.Append(@" SELECT count(*)
FROM `eagles`.`tb_oper` where  OperName=@OperName 

 ");
            dynamicParams.Add("OperName", infoOperName);

            return dbManager.ExecuteScalar<int>(sql.ToString(), dynamicParams);
        }

        public List<TbUserToken> GetUserLoginLs(GetUserLoginLsRequest requset, out int i)
        {
            var sql = new StringBuilder();
            var parameter = new StringBuilder();
            var dynamicParams = new DynamicParameters();

            var token = cacheHelper.GetData<TbUserToken>(requset.Token);

            if (token.OrgId > 0)
            {
                parameter.Append(" and  t.OrgId = @OrgId ");
                dynamicParams.Add("OrgId", token.OrgId);
            }


            if (token.BranchId > 0)
            {
                parameter.Append(" and  t.BranchId = @BranchId ");
                dynamicParams.Add("BranchId", token.BranchId);
            }


            if (!string.IsNullOrWhiteSpace(requset.UserName))
            {
                parameter.Append(" and u.Name = @Name ");
                dynamicParams.Add("Name", requset.UserName);
            }


            parameter.Append(" and  t.TokenType = 0 ");

            sql.AppendFormat(@"select count(*)
from 
eagles.tb_user_token t 
inner join eagles.tb_user_info u on t.UserId=u.UserId 
left join eagles.tb_branch b on b.BranchId=t.BranchId 
inner join eagles.tb_org_info o on o.OrgId=t.OrgId   {0} ;
 ", parameter);
            i = dbManager.ExecuteScalar<int>(sql.ToString(), dynamicParams);

            sql.Clear();

            dynamicParams.Add("pageStart", (requset.PageNumber - 1) * requset.PageSize);
            dynamicParams.Add("pageNum", requset.PageNumber);
            dynamicParams.Add("pageSize", requset.PageSize);

            sql.AppendFormat(@" select u.Name,t.CreateTime,o.OrgName,b.BranchName,u.Phone ,u.IsCustomer
from 
eagles.tb_user_token t 
inner join eagles.tb_user_info u on t.UserId=u.UserId 
left join eagles.tb_branch b on b.BranchId=t.BranchId 
inner join eagles.tb_org_info o on o.OrgId=t.OrgId  
where  1=1  {0}   order by t.CreateTime desc limit  @pageStart ,@pageSize;
 ", parameter);

            return dbManager.Query<TbUserToken>(sql.ToString(), dynamicParams);


        }
    }
}
